<template>
  <div class="app-container calendar-list-container">
    <el-row type="flex" class="row-bg" justify="end">
      <el-button type="primary" v-if="sys_menu_add" size="small" icon="el-icon-plus" @click="handlerAddTop">添加
      </el-button>
    </el-row>
    <el-row>
      <el-col :span="8" style='margin-top:15px;'>
        <el-tree
          class="filter-tree"
          node-key="id"
          highlight-current
          :data="treeData"
          :default-expanded-keys="aExpandedKeys"
          :filter-node-method="filterNode"
          :props="defaultProps"
          @node-click="getNodeData"
          @node-expand="nodeExpand"
          @node-collapse="nodeCollapse">
          <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span class="tree-node-buttons">
          <el-button type="primary" size="mini" icon="el-icon-plus" circle
                     @click.stop="() => handlerAdd(data.id)" v-if="sys_menu_add"></el-button>
          <el-button type="primary" size="mini" icon="el-icon-delete" circle
                     @click.stop="() => handleDelete(data.name, data.id)" v-if="sys_menu_del"></el-button>
        </span>
      </span>
        </el-tree>
      </el-col>
      <el-col :span="16" style='margin-top:15px;'>
        <el-card class="box-card">
          <el-form :label-position="labelPosition" label-width="80px" :model="form" ref="form">
            <el-form-item label="父菜单ID" prop="parentId">
              <el-input v-model="form.parentId" :disabled="true" placeholder="请输入菜单ID"></el-input>
            </el-form-item>
            <el-form-item label="ID" prop="id" v-if="formStatus == 'update'">
              <el-input v-model="form.id" :disabled="true" placeholder="请输入ID"></el-input>
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称"></el-input>
            </el-form-item>
            <el-form-item label="系统" prop="appName">
              <el-select class="filter-item" v-model="form.appName" placeholder="请选择系统">
                <el-option v-for="item in appOptions" :key="item" :label="item"
                           :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="权限" prop="permissions">
              <el-input v-model="form.permissions" placeholder="请输入权限"></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-select class="filter-item" v-model="form.type" placeholder="请输入资源请求类型">
                <el-option v-for="item in  typeOptions" :key="item" :label="item | typeFilter"
                           :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排序" prop="order">
              <el-input v-model="form.order" placeholder="请输入排序"></el-input>
            </el-form-item>
            <el-form-item label="前端组件" prop="component">
              <el-input v-model="form.component" placeholder="请输入描述"></el-input>
            </el-form-item>
            <el-form-item label="前端地址" prop="component">
              <el-input v-model="form.path" placeholder="访问地址"></el-input>
            </el-form-item>
            <el-form-item v-if="formStatus == 'create' && sys_menu_edit">
              <el-button type="primary" @click="create">保存</el-button>
            </el-form-item>
            <el-form-item v-else-if="sys_menu_edit">
              <el-button type="primary" @click="update">更新</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
  import {fetchTree, fetchApp, getObj, addObj, delObj, putObj} from '@/api/menu'
  import {mapGetters} from 'vuex'

  export default {
    name: 'menu',
    data() {
      return {
        list: null,
        total: null,
        formEdit: true,
        formAdd: true,
        formStatus: '',
        showElement: false,
        typeOptions: ['menu', 'button'],
        appOptions: ['无'],
        methodOptions: ['GET', 'POST', 'PUT', 'DELETE'],
        listQuery: {
          name: undefined
        },
        treeData: [],
        oExpandedKey: {},
        oTreeNodeChildren: {},
        aExpandedKeys: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        labelPosition: 'right',
        form: {
          permissions: undefined,
          name: undefined,
          appName: undefined,
          id: undefined,
          parentId: undefined,
          url: undefined,
          icon: undefined,
          order: undefined,
          component: undefined,
          type: undefined,
          path: undefined
        },
        currentId: 0,
        sys_menu_add: false,
        sys_menu_edit: false,
        sys_menu_del: false
      }
    },
    filters: {
      typeFilter(type) {
        const typeMap = {
          menu: '菜单',
          button: '按钮',
          true: '启用',
          false: '禁用'
        }
        return typeMap[type] ? typeMap[type] : typeMap[type]
      }
    },
    created() {
      this.getList()
      this.getAppList()
      this.sys_menu_add = this.permissions['sys_menu_add']
      this.sys_menu_edit = this.permissions['sys_menu_edit']
      this.sys_menu_del = this.permissions['sys_menu_del']
    },
    computed: {
      ...mapGetters([
        'elements',
        'permissions'
      ])
    },
    methods: {
      getList() {
        fetchTree(this.listQuery).then(response => {
          this.treeData = response.data.data
        })
      },
      getAppList() {
        fetchApp().then(response => {
          this.appOptions = response.data.data
        })
      },
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      nodeExpand(data) {
        let aChildren = data.children
        if (aChildren.length > 0) {
          this.oExpandedKey[data.id] = true
          this.oTreeNodeChildren[data.id] = aChildren
        }
        this.setExpandedKeys()
      },
      nodeCollapse(data) {
        this.oExpandedKey[data.id] = false
        // 如果有子节点
        this.treeRecursion(this.oTreeNodeChildren[data.id], (oNode) => {
          this.oExpandedKey[oNode.id] = false
        });
        this.setExpandedKeys()
      },
      setExpandedKeys() {
        let oTemp = this.oExpandedKey
        this.aExpandedKeys = []
        for (let sKey in oTemp) {
          if (oTemp[sKey]) {
            this.aExpandedKeys.push(parseInt(sKey));
          }
        }
      },
      treeRecursion(aChildren, fnCallback) {
        if (aChildren) {
          for (let i = 0; i < aChildren.length; ++i) {
            let oNode = aChildren[i]
            fnCallback && fnCallback(oNode)
            this.treeRecursion(oNode.children, fnCallback)
          }
        }
      },
      getNodeData(data) {
        if (!this.formEdit) {
          this.formStatus = 'update'
        }
        getObj(data.id).then(response => {
          let data = response.data.data
          this.form = data
        })
        this.currentId = data.id
        this.showElement = true
      },
      handlerEdit() {
        if (this.form.id) {
          this.formEdit = false
          this.formStatus = 'update'
        }
      },
      handlerAddTop() {
        this.currentId = 0
        this.handlerAdd()
      },
      handlerAdd(id) {
        id && (this.currentId = id)
        this.resetForm()
        this.formEdit = false
        this.formStatus = 'create'
      },
      handleDelete(name, id) {
        this.$confirm('此操作将永久删除' + name + ', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delObj(id).then(() => {
            this.getList()
            this.resetForm()
            this.onCancel()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
      },
      update() {
        putObj(this.form).then(() => {
          this.getList()
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      create() {
        addObj(this.form).then(() => {
          this.getList()
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      resetForm() {
        this.form = {
          permission: undefined,
          name: undefined,
          menuId: undefined,
          parentId: this.currentId,
          url: undefined,
          icon: undefined,
          sort: undefined,
          component: undefined,
          type: undefined,
          method: undefined,
          path: undefined
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .custom-tree-node {
    flex: 1;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
    -ms-flex-pack: justify;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .tree-node-buttons {
    display: none;
  }

  .custom-tree-node:hover .tree-node-buttons {
    display: block;
  }
</style>
